package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.MenuService;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService
{
    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private MenuService menuService;

    public User findByUsername(String username) {
        //根据名字查用户信息
        User user = userDao.findByUsername(username);
        if(user == null){
            return null;
        }
        //获得用户id
        Integer userId = user.getId();
        //根据用户id获得角色信息
        Set<Role> roles = roleDao.findByUserId(userId);
        //判断角色不为空
        if(roles != null && roles.size()>0){
            //遍历获得所有角色
            for (Role role : roles) {
                //获得角色id
                Integer roleId = role.getId();
                //通过角色id获得权限信息
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                //判断权限不为空
                if(permissions != null && permissions.size()>0){
                    //给角色赋予权限
                    role.setPermissions(permissions);
                }
            }
            //给用户赋予角色
            user.setRoles(roles);
        }
        //返回用户
        return user;
    }

    @Override
    public List<User> findUser() {
        return userDao.userList();
    }

    @Override
    public List<User> userList() {
        return userDao.userList();
    }

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<User> page = userDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(User user, Integer[] roleIds) {
        String encodedPassword=new BCryptPasswordEncoder().encode(user.getPassword());
        user.setPassword(encodedPassword);
        //调用dao方法
        userDao.add(user);
        //调用自定义方法添加检查组和检查项的级联组
        setUserAndRole(user.getId(),roleIds);
        menuService.getAllMenusForCurrentUser(user.getUsername());
    }

    @Override
    public void edit(User user, Integer[] roleIds) {
        userDao.deleteAssociation(user.getId());
        setUserAndRole(user.getId(),roleIds);
        userDao.edit(user);
        menuService.getAllMenusForCurrentUser(user.getUsername());
    }

    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public List<Integer> findRolesByUserId(Integer id) {
        return userDao.findRolesByUserId(id);
    }

    @Override
    public void delete(Integer id) {
        userDao.deleteAssociation(id);
        userDao.delete(id);
        User user = userDao.findById(id);
        jedisPool.getResource().del(user.getUsername());
    }

    //自定义添加用户和角色的级联组
    public void setUserAndRole(Integer userId,Integer[] roleIds){
        if(roleIds !=null && roleIds.length>0){
            for(Integer roleId : roleIds){
                Map<String,Integer> map = new HashMap<>();
                map.put("user_id",userId);
                map.put("role_id",roleId);
                userDao.setUserAndRole(map);
            }
        }
    }
}
